package com.tdam2011.grupo02.ui;

import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Map.Entry;

import android.content.ContentUris;
import android.content.Context;
import android.database.Cursor;
import android.net.Uri;
import android.provider.ContactsContract;
import android.util.Log;

import com.tdam2011.grupo02.domain.ContactImageUri;

public class ContactsManager {

	private Context context;
	private HashMap<String, ContactImageUri> imgUri;
	private static final String TAG = "ContactsManager";

	public ContactsManager(Context context) {
		this.context = context.getApplicationContext();
		loadContactsImageUri();
	}

	private void loadContactsImageUri() {
		Uri uri = ContactsContract.Contacts.CONTENT_URI;
		Uri imgContacto;
		String id;
		String nombre;
		ContactImageUri aux;

		imgUri = new HashMap<String, ContactImageUri>();

		String[] projection = new String[] { ContactsContract.Contacts._ID,
				ContactsContract.Contacts.DISPLAY_NAME };
		String selection = ContactsContract.Contacts.HAS_PHONE_NUMBER + " = ? ";
		String[] selectionArgs = new String[] { "1" };
		String sortOrder = ContactsContract.Contacts.DISPLAY_NAME + " ASC";

		 Cursor cursor = context.getContentResolver().query(uri, projection,
		 selection,
		 selectionArgs, sortOrder);

		while (cursor.moveToNext()) {

			id = cursor.getString(cursor
					.getColumnIndex(ContactsContract.Contacts._ID));
			nombre = cursor.getString(cursor
					.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME));

			imgContacto = Uri.withAppendedPath(ContentUris.withAppendedId(
					ContactsContract.Contacts.CONTENT_URI, Long.parseLong(id)),
					ContactsContract.Contacts.Photo.CONTENT_DIRECTORY);

			aux = new ContactImageUri();
			aux.setId(id);
			aux.setNombre(nombre);
			aux.setImg(imgContacto);

			Log.e(TAG, "ID = " + aux.getId() + " - NOMBRE = " + aux.getNombre());

			imgUri.put(id, aux);
		}
	}

	public String getContactNameById(String id) {
		ContactImageUri aux = imgUri.get(id);
		Log.e(TAG, "ID PARAMETRO = " + id);
		if (aux != null)
			return aux.getNombre();

		return null;
	}

	public Uri getImageUriByContact(String nombre) {
		if (nombre != null) {
			Iterator<Entry<String, ContactImageUri>> iterator = imgUri.entrySet().iterator();
			ContactImageUri aux;

			while (iterator.hasNext()) {
				Map.Entry<String, ContactImageUri> e = iterator
						.next();
				aux = (ContactImageUri) e.getValue();
				if (aux.getNombre().equals(nombre))
					return aux.getImg();
			}
		}

		return null;
	}

}
